package com.example.javademo.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.javademo.sys.entity.PageDTO;
import com.example.javademo.sys.entity.UserQuery;
import com.example.javademo.sys.entity.userInfo;
import com.example.javademo.sys.mapper.userMapper;
import com.example.javademo.sys.service.IuserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class userService extends ServiceImpl<userMapper, userInfo> implements IuserService {
    @Autowired
    private userMapper mUserMapper;

    @Override
    public userInfo login(userInfo user) {
        // 根据用户名查询
        LambdaQueryWrapper<userInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userInfo::getUserName, user.getUserName());
        userInfo loginUser = mUserMapper.selectOne(wrapper);
        return loginUser;
    }

    @Override
    public userInfo register(userInfo user) {
        LambdaQueryWrapper<userInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userInfo::getUserName, user.getUserName());
        userInfo loginUser = mUserMapper.selectOne(wrapper);
        if(loginUser==null){
           int index= mUserMapper.insert(user);
           if(index==-1){
               return null;
           }else {
               return user;
           }
        }else {
            return null;
        }
    }

    @Override
    public PageDTO<userInfo> queryUsersPage(UserQuery query) {
        // 1. 准备分页条件
        Page<userInfo> p = query.toMpPageDefaultSortByCreateTimeDesc();
        // 2. 分页查询
        if (query.getName() != null) {
            LambdaQueryWrapper<userInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(userInfo::getUserName, query.getName());
            this.page(p, wrapper);
        }else {
            this.page(p);
        }
        // 3. 封装返回
        return PageDTO.of(p, userInfo.class);
    }

}
